import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;

/*
 * Some combination of Item Mean, Mode and Median
 */
public class AIMMM extends Scheduler implements Runnable {
	int start;
	int stop;
	byte[] BLOCK;

	public AIMMM(int start, int stop) {
		this.start = start;
		this.stop = stop;
	}

	void writeBlock() {
		String FILE_NAME = String.format("%s%07d.bin", BLOCK_PATH, start);		File out = new File(FILE_NAME);
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Done writing: " + FILE_NAME + " @ "
				+ this.getClass());
	}

	@Override
	public void run() {
		int ilen = USERB[0].ilen;
		BLOCK = new byte[(stop - start) * ilen];

		int c = 0;
		for (int bUserID = start; bUserID < stop; bUserID++) {
			for (int i = 0; i < ilen; i++) {
				int bItemID = USERB[bUserID].items[i];
				byte[] votes = ITEMA[bItemID].votes;
				Arrays.sort(votes);
				int uilen = ITEMA[bItemID].ulen;
				byte pred = 0;

				byte median = 0;
				if (uilen % 2 == 0) {
					median = (byte) ((votes[uilen/2] + votes[uilen/2 + 1])/2);
				} else {
					median = votes[uilen/2];
				}
				byte mean = (byte) ITEMA[bItemID].mean;
				int[] mode = new int[101];
				for (int v : ITEMA[bItemID].votes) {
					mode[v]++;
				}
				byte modeVote = 0;
				int modeNum = 0;
				for (int m = 0; m < 101; m++) {
					if (mode[m] > modeNum) {
						modeVote = (byte) m;
						modeNum = mode[m];
					}
				}
				
				
				if (modeNum > uilen/3) {
					pred = modeVote;
				} else if (Math.abs(mean - median) > 15) {
					pred = median;
				} else {
					pred = mean;
				}
				BLOCK[c * ilen + i] = pred;
			}
			c++;
		}

		writeBlock();
	}
}
